$(function(){
	showCondition(true, 1, 0, 1, [1, 1, 0, 0, 0,0]);//加载查询条件
	tabId=$("#tabContent > .tab-pane.active").attr("id");
	paramTabPage[tabId]=$("#tabContent > .tab-pane.active").data();
	var totalQuota = [
	                  {name:"产能指标", 
	                   data:[
	                         {"quotaCode":"TotalCaseCnt", "quotaName":"患者数"}, 
	                         {"quotaCode":"TotalFee", "quotaName":"总费用(万元)"},
	                         {"quotaCode":"AvgFee", "quotaName":"次均费用(元)"},
	                         {"quotaCode":"DrugFee", "quotaName":"药品费用(万元)"}, 
	                         {"quotaCode":"DrugRatio", "quotaName":"药占比(%)"},
	                         {"quotaCode":"MaterialFee", "quotaName":"耗材费(万元)"}, 
	                         {"quotaCode":"MaterialRatio", "quotaName":"耗占比(%)"},
	                         {"quotaCode":"OrderQuantity", "quotaName":"医嘱项数"}
	                         ]
	                  }
	                  ];
	
	
	$(document).ajaxStop(function(){
		
		reloadNav();
	});
	$('#'+tabId+' .currDepOrDepgroup').html('<i class="fa fa-stethoscope"></i>'+paramTabPage[tabId].ddesc);
	loadQuotaData(paramTabPage[tabId].mtype, paramTabPage[tabId].ddesc);//加载科室或主诊组表格
	loadDisQuotaData(paramTabPage[tabId].mtype, paramTabPage[tabId].ddesc);//加载科室病组或主诊组病组表格
	
	function loadQuotaData(monitorType,name){
		
		var ccode='';
		var ddesc='';
		if(monitorType=="depGroup"){
			ccode=paramTabPage[tabId].pardepgroupCode;
			ddesc=name;
		 }
		 if(monitorType=="dep"){
			 ccode=paramTabPage[tabId].pardepCode;
			 ddesc=name;
		 }
		 if(monitorType=="hosp"){
			 ddesc='全院';
		 }
		 if(monitorType=='clinic'){
			 ccode=paramTabPage[tabId].ccode;
			 ddesc=paramTabPage[tabId].ddesc;
		 }
		 $('#'+tabId+' .depName').html(ddesc);
		 var theadStr = '<tr>';
		 var tbodyStr = '<tr>';
		 var quotas = totalQuota[0].data;
		 for(var o in quotas){
			 theadStr+='<td>'+quotas[o].quotaName+'</td>';
			 tbodyStr+='<td id="'+quotas[o].quotaCode+'-td">'+getData(monitorType,quotas[o].quotaCode,quotas[o].quotaName,function(value,valuecc,code,desc){
				 if(desc.indexOf("%")>-1){
					 $('#'+tabId+' #'+code+'-td').html(comparePercent(value,valuecc));
				 }else{
					 $('#'+tabId+' #'+code+'-td').html(compareValue(value,valuecc));
				 }
			 })+'</td>';
		 }
		theadStr+='</tr>';
		tbodyStr+='</tr>';
		$('#'+tabId+' #depDrgDatatable thead').html(theadStr);
		$('#'+tabId+' #depDrgDatatable tbody').html(tbodyStr);
	}
	function getData(monitorType,quotaCode,quotaName,callback){
		var param=drgUI.setAjaxData(tabId);
		param.monitorType=monitorType;
	    param.quotaCode=quotaCode;
		$.post(contextPath+"/DrgsIndexCal/indexCal.dhc", param).done(function(data){
			if(data.data.length>0){
				data = data.data[0];
				callback(data.QuotaValue,data.QuotaValuecc,quotaCode,quotaName);
			}else{
				callback("","",quotaCode,quotaName);
			}
			return '-';
		});
	}
	/**
	 * 获取科室下病组或主诊组下病组数据
	 */
	function loadDisQuotaData(monitorType,name){
		var quotas = totalQuota[0].data;
		var ajaxCount = quotas.length;
		drgsQuotaData=[];//表格数据
		drgsQuotaColumns = [ {
			"data" : null,
			"className" : "details-control",
			"width" : 25
		}, {
			"data" : "ccode1",
			"title" : "DRG病组",
			"render":function(obj,type,full){
				return "<span title=\""+full.ddesc+"\">"+full.ccode+"</span><span style=\"display:none\">-"+full.ddesc+"<span>";
			}
		}
		];//表格列
		for(var o in quotas){
			(function(o){//解决for循环闭包问题
				var quotaCode = quotas[o].quotaCode;
				var quotaName = quotas[o].quotaName;
				
				if(quotaName.indexOf("%")>-1){//如果是比率类指标
					var column = { "data": quotaCode,"type":"number-html","title":quotaName,
							"render":function(obj, type, full){
								return formatNumber(full[quotaCode])+gridcompareValuePercent(full[quotaCode],full[quotaCode+"cc"]);
							}};
					drgsQuotaColumns.push(column);
				}
				else{
					var column = { "data": quotaCode,"type":"number-html","title":quotaName,
							"render":function(obj, type, full){
								return formatNumber(full[quotaCode])+gridcompareValue(full[quotaCode],full[quotaCode+"cc"]);
							}};
					drgsQuotaColumns.push(column);
				}
				
				buildDRGQuotaData(quotaCode,quotaName);
			})(o);
		}
		//查询科室下病组或主诊组下病组数据
		function buildDRGQuotaData(quotaCode,quotaName){
			var param=drgUI.setAjaxData(tabId);
			param.monitorType='drgs';
		    param.quotaCode=quotaCode;
			$.post(contextPath + "/DrgsIndexCal/indexCal.dhc",param,function(result){
				ajaxCount--;
				drgQuotaDataCallback(quotaCode,quotaName,result.data);
			});
		}
		//科室下病组数据查询后的回调函数，拼接数据
		var drgQuotaDataCallback=function(quotaCode,quotaName,quotaData){
			if(drgsQuotaData.length==0){//第一次push数据时，要添加ccode、ddesc
				for(var o in quotaData){
					var tmpCode = quotaData[o]["ccode"];
					var tmpdesc = quotaData[o]["ddesc"];
					var tmpQV = quotaData[o]["QuotaValue"];
					var tmpQVCC = quotaData[o]["QuotaValuecc"];
					var tmpStr = "{'ccode':'"+tmpCode+"','ddesc':'"+tmpdesc+"','"+quotaCode+"':'"+tmpQV+"','"+quotaCode+"cc':'"+tmpQVCC+"'}";
					var jsonobj=eval('('+tmpStr+')');
					drgsQuotaData[o]=jsonobj;
				}
			}else{
				for(var o in quotaData){
					var tmpDrgsdata = [];
					if(drgsQuotaData[o]){
						tmpDrgsdata = drgsQuotaData[o];
					}else{
						tmpDrgsdata = [];
						tmpDrgsdata["ccode"]=quotaData[o]["ccode"];
						tmpDrgsdata["ddesc"]=quotaData[o]["ddesc"];
					}
					tmpDrgsdata[quotaCode]=quotaData[o]["QuotaValue"];
					tmpDrgsdata[quotaCode+"cc"]=quotaData[o]["QuotaValuecc"];
					drgsQuotaData[o]=tmpDrgsdata;
				}
			}
		};
		//如果数据查询完，则继续执行
		var timerId = window.setInterval(function(){
			if(ajaxCount==0){
				window.clearInterval(timerId);
				var column = { "data": "OPERATION","title":'操作',"className":"feeStageOper",
			           	 "render":function(obj, type, full){
			           		return "<a>医嘱</a>";
			        	 }
			         };
				drgsQuotaColumns.push(column);
				
				$("#"+tabId+" #depDrgTableDiv").html('<table id="depDrgTable" class="table display"></table>');
				var paramsDatatables={tableTitle:paramTabPage[tabId].ddesc+'下病组指标情况表',order:[1,'asc'],columnDefs:[{orderable:false,targets:[0]}]};
				var oTable =$("#"+tabId+" #depDrgTableDiv #depDrgTable").dataTableBasic(drgsQuotaColumns,drgsQuotaData,paramsDatatables);
				$("#"+tabId+" #depDrgTableDiv #depDrgTable").off('click');
				$("#"+tabId+" #depDrgTableDiv #depDrgTable").on('click','.feeStageOper a',function(){
					var nTr = $(this).closest('tr');
					var row = oTable.row( nTr );
					var rowData=row.data();
					orderDetail(rowData.ccode, rowData.ddesc,'','', 'drg');
				});
				
				function format ( d ) {
				    return '<div class="col-xs-12" id="'+tabId+d.ccode+'">'
				           +'	<div class="row">'
				           +'		<div class="col-xs-6"><div class="stagePie" style="height:260px;"></div></div>'
				           +'		<div class="col-xs-6"><div class="stageLine" style="height:260px;"></div></div>'
				           +'	</div>'
				           +'   <div class="row">'
				           +'		<div class="col-xs-12">'
				           +'			<div class="stageTableDiv paddingd10"></div>'
				           +'     	</div>'
				           +'   </div>'
				           +'</div>';
				}
				//病组点击事件，查询病组下的分段科室的指标
				$('#'+tabId+' #depDrgTable tbody').off('click', 'td.details-control');
				$('#'+tabId+' #depDrgTable tbody').on('click', 'td.details-control', function () {
					var nTr = $(this).closest('tr');
					var row = oTable.row( nTr );
					var aData=row.data();
					if (row.child.isShown()){ //判断是否已打开
						row.child.hide();
						nTr.removeClass("shown");
					} else {
						nTr.addClass("shown");
						row.child(format(aData)).show();
						echartLoadingInit($('#'+tabId+' #'+tabId+aData.ccode+' .stageLine'));//loading效果
						echartLoadingInit($('#'+tabId+' #'+tabId+aData.ccode+' .stagePie'));//loading效果
						 //分段科室表格
				        var tid='id'+new Date().getTime();
				        $('#'+tabId+' #'+tabId+aData.ccode+' .stageTableDiv').html('<table id="'+tid+'" class="table"></table>');
				        var param=drgUI.setAjaxData(tabId);
						param.monitorType=monitorType;
						param.type1=paramTabPage[tabId]['orderSpecialDep']==''?"":paramTabPage[tabId].orderSpecialDep+",'"+paramTabPage[tabId].depName+"'";;
						param.pardrgCode=aData.ccode;
				        $.post(contextPath+"/feeStage/getFeeStageData.dhc",param).done(function(data){
							data = data.data;
							var columns = [
											{ "data": "STAGEDEP","title":"部门"},
						                    { "data": "TOTALCASECNT","type":"number-html","title":"患者数",
						                      "render": function(obj, type, full) {
						                    	  return compareValue(full.TOTALCASECNT, full.TOTALCASECNTcc);
						                      }
						                    },
						                    { "data": "STAGEFEE","type":"number-html","title":"分段费用(万元)",
						                      "render": function(obj, type, full) {
						                    	  return compareValue(full.STAGEFEE, full.STAGEFEEcc);
						                      }
						                    },
						                    { "data": "StageRatio","type":"number-html","title":"分段费用占比(%)",
						                      "render": function(obj, type, full) {
						                    	  return compareValue(full.STAGERATIO, full.STAGERATIOcc);
						                      }
						                    },
						                    { "data": "AvgFee","type":"number-html","title":"次均费用(元)",
						                      "render": function(obj, type, full) {
						                    	  return compareValue(full.AVGFEE, full.AVGFEEcc);
						                      }
						                    },
						                    { "data": "DrugFee","type":"number-html","title":"药品费用(万元)",
						                      "render": function(obj, type, full) {
						                    	  return compareValue(full.DRUGFEE, full.DRUGFEEcc);
						                      }
						                    },
						                    { "data": "DrugRatio","type":"number-html","title":"药占比(%)",
						                      "render": function(obj, type, full) {
						                    	  return comparePercent(full.DRUGRATIO, full.DRUGRATIOcc);
						                      }
						                    },
						                    { "data": "MaterialFee","type":"number-html","title":"耗材费(万元)",
						                      "render": function(obj, type, full) {
						                    	  return compareValue(full.MATERIALFEE, full.MATERIALFEEcc);
						                      }
						                    },
						                    { "data": "MaterialRatio","type":"number-html","title":"耗占比(%)",
						                      "render": function(obj, type, full) {
						                    	  return comparePercent(full.MATERIALRATIO, full.MATERIALRATIOcc);
						                      }
						                    },
						                    { "data": "OrderQuantity","type":"number-html","title":"医嘱项数",
							                      "render": function(obj, type, full) {
							                    	  return compareValue(full.ORDERQUANTITY, full.ORDERQUANTITYcc);
							                      }
						                    },
						                    { "data": "OPERATION","title":"操作","className":"feeStageOperStage",
						                      "render": function(obj, type, full) {
						                    	  return "<a>医嘱</a>";
						                      }
						                    }
						                 ];
							var paramsDatable={searching:false,paging:false,info:false,lengthChange:false,tableTitle:paramTabPage[tabId].ddesc+''+aData.ccode+'病组指标情况表',order:[2,'desc'],columnDefs:[{orderable:false,targets:[0,10]}]};
							if(data.length>12){
								paramsDatable.scrollY='350px';
							}
							var depTable=$('#'+tabId+' #'+tabId+aData.ccode+' #'+tid).dataTableBasic(columns,data,paramsDatable);
							$('#'+tabId+' #'+tabId+aData.ccode+' #'+tid).off('click');
							$('#'+tabId+' #'+tabId+aData.ccode+' #'+tid).on('click','.feeStageOperStage a',function(){
								var nTr = $(this).closest('tr');
								var row = depTable.row( nTr );
								var rowData=row.data();
								//特殊部门未配置且，当前分段科室为其他时，需特殊处理,拼接现有表格中除其他以外的分段科室
								if(rowData.DEPCATE=='OTHER'&&paramTabPage[tabId].orderSpecialDep==''){
									var noStageDepDescArray=[];
									var tableData=depTable.data().toArray();
									for(var o in tableData){
										if(tableData[o].DEPCATE!='OTHER'){
											noStageDepDescArray.push("'"+tableData[o].STAGEDEP+"'");
										}
									}
									var noStageDepDesc=noStageDepDescArray.join(",");
									orderDetail(aData.ccode,aData.ddesc,rowData.DEPCATE, rowData.STAGEDEP,'stageDep',noStageDepDesc);
								}
								else{
									orderDetail(aData.ccode,aData.ddesc,rowData.DEPCATE, rowData.STAGEDEP,'stageDep');
								}
							});
							var stageFeeData = [];
							var avgFeeData = [];
							var drugRatioData = [];
							var avgFeeDatacc = [];
							var drugRatioDatacc = [];
							var stageDepData = [];
							for(var n in data){
								stageFeeData.push({name:data[n].STAGEDEP,value:data[n].STAGEFEE});
								avgFeeData.push(data[n].AVGFEE);
								drugRatioData.push(data[n].DRUGRATIO);
								avgFeeDatacc.push(data[n].AVGFEEcc);
								drugRatioDatacc.push(data[n].DRUGRATIOcc);
								stageDepData.push(data[n].STAGEDEP);
							}
							
							var charParams={pagemode:true};
							pieCharts($('#'+tabId+' #'+tabId+aData.ccode+' .stagePie'), stageFeeData, '特殊部门费用分布图', '',charParams);
							var legend=['次均费用(本期)','次均费用('+compareName+')','药占比(本期)','药占比('+compareName+')'];
							var xAxis = [{type : 'category',data : stageDepData}];
							var yAxis = [{type : 'value',name : '次均费用',splitNumber:5,axisLabel : {formatter: '{value} 元'}},
								        {type : 'value',name : '药占比',splitLine:{show:false},axisLabel : {formatter: '{value} %'}}];
							var series = [
									        {name:'次均费用(本期)',type:'bar',data:avgFeeData},
									        {name:'次均费用('+compareName+')',type:'bar',data:avgFeeDatacc},
									        {name:'药占比(本期)',type:'line',yAxisIndex: 1,data:drugRatioData},
									        {name:'药占比('+compareName+')',type:'line',yAxisIndex: 1,data:drugRatioDatacc}
									    ];
							var chartParams={};
							barLineMixChartBasic($('#'+tabId+' #'+tabId+aData.ccode+' .stageLine'), legend,series,xAxis,yAxis,'特殊部门次均费用和药占比','',chartParams);
						});
					}
			       
			    } );
			}
		},1000);
	}
	//医嘱弹出框
	function orderDetail(typeCode,typeDesc,stageDepCode, stageDepDesc, type,noStageDepDesc){
		var param=drgUI.setAjaxData(tabId);
		 param.pardrgCode=typeCode;
		 if(type=="stageDep"){
			 if(stageDepCode=='OTHER'){//如果是其他，则传入特殊部门
				 if(paramTabPage[tabId].orderSpecialDep==''){//没有配置特殊部门时
					 param.type1=noStageDepDesc;
				 }
				 else{
					 param.type1=paramTabPage[tabId].orderSpecialDep+",'"+paramTabPage[tabId].depName+"'";
				 }
				
			 }
			 else{
				 param.type1=stageDepDesc;
			 }
		 }
		 $.post(contextPath + '/pages/common/top-dialog.jsp').done(function(data){
				var dialog  = $(data);
				dialog.find(".modal-title").html(typeCode+'-'+(stageDepDesc==""?"":(stageDepDesc+"-"))+"医嘱项明细");
				dialog.find(".modal-body").css("min-height", "440px");
				dialog.find(".modal-body").css("width", "60%");
				dialog.modal({
					keyboard: false
				}).on({
					'hidden.bs.modal' : function(){
						$(this).remove();
					},
					'shown.bs.modal' : function(){
						$.post(contextPath + "/feeStage/getOrderData.dhc",param).done(function(data){
							var data = data.data;
							//分段科室表格
							dialog.find(".echartscq").html('<table class="table display nowrap"></table>')
							var columns = [
											{ "data": "ORDERID","title":"医嘱序号"},
						                    { "data": "ORDERDESC","title":"医嘱项名称","render": function(obj, type, full) {
							   	            	 return linefeedText(obj);
							   	            }
											},
						                    { "data": "ORDERTOTALFEE","title":"医嘱总额(元)",
						                    	"render":function(obj, type, full){
						                    		return formatNumber(full.ORDERTOTALFEE);
						                    	}
						                    },
						                    { "data": "ORDERFEERATIO","title":"金额占比(%)"},
						                    { "data": "AvgOrderFee","title":"次均医嘱金额(元)",
						                    	"render":function(obj, type, full){
						                    		return formatNumber(full.AVGORDERFEE);
						                    	}
						                    },
						                    { "data": "OrderUnitPrice","title":"单价",
						                    	"render":function(obj, type, full){
						                    		return formatNumber(full.ORDERUNITPRICE);
						                    	}
						                    },
						                    { "data": "CaseCnt","title":"使用人次",
						                    	"render":function(obj, type, full){
						                    		return formatNumber(full.CASECNT);
						                    	}
						                    },
						                    { "data": "OrderQuantity","title":"医嘱数量",
						                    	"render":function(obj, type, full){
						                    		return formatNumber(full.ORDERQUANTITY);
						                    	}
						                    }
						                 ];
								var paramsDatatable={scrollY:'300px'};
								dialog.find(".echartscq").find('table').dataTableBasic(columns, data,paramsDatatable);
						   });
					}
				});
		 });
	}
});